package com.banzhi.shop.activity;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Management.Management_Data;
import com.banzhi.shop.model.CallBack.GoodsPaixuCallBack;
import com.banzhi.shop.model.CallBack.ManagementCallBack;
import com.banzhi.shop.model.IGoodsPaixuModel;
import com.banzhi.shop.model.IManagementModel;
import com.banzhi.shop.model.Impl.GoodsPaixuImpl;
import com.banzhi.shop.model.Impl.ManagementImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品排序
 */
public class GoodsPaixuActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, ManagementCallBack, View.OnClickListener, GoodsPaixuCallBack {
    /**
     * 退出
     */
    private ImageView ivback;

    /**
     * 获取列表信息的实体类集合
     */
    private List<Management_Data> magData = new ArrayList<>();
    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout srlayout;
    //    private int page = 1;
    private RelativeLayout rlnodata;
    private IManagementModel model;
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private CommonHeadAdapter<Management_Data> adapter;
    private TextView tvtrue;
    private JSONObject jsonObject;
    private String[] strs;
    private IGoodsPaixuModel paixumodel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_paixu);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        model = new ManagementImpl();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(this);
        paixumodel = new GoodsPaixuImpl();
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        srlayout = (SwipeRefreshLayout) findViewById(R.id.srlayout);
        srlayout.setColorSchemeResources(R.color.themeColor);
        srlayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        srlayout.setOnRefreshListener(this);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        tvtrue = (TextView) findViewById(R.id.tv_true);
        jsonObject = new JSONObject();
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        tvtrue.setOnClickListener(this);
    }

    private boolean isalltrue = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_true:
                isalltrue = true;
                for (int i = 0; i < strs.length; i++) {
                    if ("0".equals(strs[i])) {
                        isalltrue = false;
                    }
                }
                if (isalltrue) {
                    try {
                        for (int i = 0; i < strs.length; i++) {
                            jsonObject.put(magData.get(i).getId() + "", Integer.parseInt(strs[i]));
                        }
                        Log.d("排序的数据：", "排序的数据：" + jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    paixumodel.getData(jsonObject.toString(), this);
                } else {
                    ToastUtils.makeToastShort("排序数字不得输入0");
                }
                break;
        }
    }

    @Override
    public void onRefresh() {
//        page = 1;
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(this);
    }

    private void showView() {
        if (adapter == null) {
            adapter = new CommonHeadAdapter<Management_Data>(this, R.layout.items_management_paixu, magData) {
                @Override
                public void convert(final ViewHolder holder, Management_Data management_data, final int position) {
                    ((EditText) (holder.getView(R.id.et_text))).setText(position + 1 + "");
                    ((EditText) (holder.getView(R.id.et_text))).setSelection(((EditText) (holder.getView(R.id.et_text))).getText().length());
                    holder.setText(R.id.tv_name, management_data.getTitle());
                    if (ASUtils.isCanUse(management_data.getThumb())) {
                        Picasso.with(GoodsPaixuActivity.this).load(management_data.getThumb()).placeholder(R.mipmap.zhanweitu2).into(holder.getImageView(R.id.iv_image));
                    }
                    ((EditText) (holder.getView(R.id.et_text))).addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            strs[position] = ((EditText) (holder.getView(R.id.et_text))).getText().toString().trim();
//                            ToastUtils.makeToastShort(strs[position]);
                        }
                    });
                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void ongetDataSuccess(Object object) {
        if (srlayout.isRefreshing()) {
            srlayout.setRefreshing(false);
        }
        List<Management_Data> datas = (List<Management_Data>) object;
        magData.clear();

        magData.addAll(datas);

        if (magData.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }

        showView();
        if (strs == null) {
            strs = new String[magData.size()];
            for (int i = 0; i < magData.size(); i++) {
                strs[i] = i + 1 + "";
            }
        }
        LoadingDialogUtils.dismiss();
    }


    @Override
    public void ongetDataError(Object object) {
        if (srlayout.isRefreshing()) {
            srlayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();
    }

    @Override
    public void deleteGoodsSuccess(Object object) {

    }

    @Override
    public void deleteGoodsError(Object object) {

    }


    @Override
    public void paixuSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        finish();
    }

    @Override
    public void paixuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

}
